'use strict';
if ( ! ''.trim || ! document.querySelectorAll || ! document.querySelectorAll.bind || ! Object.keys )
   document.getElementById('msg_upgrade_browser').style.display = 'block';

var _ = document.querySelectorAll.bind( document );
var make = document.createElement.bind( document );

var shdic={};

shdic.log = (function ()
{
    var _debug = true;
    return {
        debug:function(m){
        	try{
        		if(_debug){
        			alert(m);
        		}
        	}catch(e){};
        	return false;
        }
    };

})();	//shdic.log end.

shdic.pub = (function ()
{
    return {
        nr: function (msg)
        {
            var tt = '';
            if(msg) tt=msg;
            alert('Not Ready! '+tt);
            return ;

        },drop_last:function(s,n){
        	if(!n) n=1;
        	return s.substring(0,s.length-n);

        },cint:function(n){
        	var t=0;
        	try{
        		t=parseInt(n);        		
        	}catch(e){};        	
        	return t;
        }
    };

})();	//shdic.pub end.

/**
 * 对用户在TextArea中输入的数据进行过滤，把< -> <等操作，以及逆向操作
 */
shdic.htmlFilter = (function ()
{
    /**
     * 转化textarea中的空格为$nbsp;
     * \n转化为<br/>
     * @private
     */
    function _transSpace(data)
    {
        return data.replace(/\n/g, "<br/>").replace(/\s/g, " ");
    };
    /**
     * 转化所有尖括号
     * @private
     */
    function _transBrace(data)
    {
        return data.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    };
    function _resumeSpace(data)
    {
        return data.replace(/ /g, " ").replace(/<br\s*\/>/ig, "\n");
    };
    function _resumeBrace(data)
    {
        return data.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
    };

    return {
        txt2Html: function (data)
        {
            return _transSpace(_transBrace(data));

        }, html2Txt: function (data)
        {
            return _resumeSpace(_resumeBrace(data));
        }
    };

})();


function str2json(data){
	if(data==undefined) return null;
	try{
		var dataObj=eval("("+data+")");//转换为json对象
		return dataObj;
	}catch(e){		
		alert('Error ! in function str2json !');
		alert(e.name + ": " + e.message);
		if(data.length>0) alert(data);
		else if (data.length<1) alert("[data] is empty!");
		console.log(data);
		return null;
	}   
}

function getJsonAtt(json,att){
	return getAtt(json,att);
   // if(!json) return '';
   // var ret = '';
   // $.each(json,function(idx,item){ 
   //    if(idx==att){
   //       ret = item;
   //       // break;
   //       return false;
   //    }
   // });
   // return ret;
}

function getAtt(json,att){
	if(!json) return '';
	var ret = '';
	for (var idx in json){
		var item=json[idx];
		if(idx==att){
			ret = item;
			break;
			// return false;
		}
	}
	return ret;
}

function getIdxByAtt(json,att){
    if(!json) return '';
    var ret = '';
    for (var idx in json){
        var item=json[idx];
        if(item==att){
            ret = idx;
            // break;
            // return false;
        }
    }
    return ret;
}

function deepClone(obj){
   function Clone(){};
   Clone.prototype = obj;
   var o = new Clone();
   for(var a in o){
      if(typeof o[a] == "object") {
         o[a] = deepClone(o[a]);
      }
   }
   return o;
}


function errMsg(msg,t){
	if(!t){
    	t=1500;
    }else if(t<10){
  		t=t*1000;
    }
	$("#div_errormsg").show();
	$("#errormsg").html(msg).show(300).delay(t).hide(300); 
	// alert("aa");
	setTimeout(function(){
		$("#div_errormsg").hide();
	},+t+600);
	
}

function okMsg(msg,t){
    if(!t){
        t=1500;
    }else if(t<10){
        t=t*1000;
    }
    $("#div_okmsg").show();
    $("#okmsg").html(msg).show(300).delay(t).hide(300); 
    // alert("aa");
    setTimeout(function(){
        $("#div_okmsg").hide();
    },+t+600);
    
}

$.ajaxSetup
({
  dataType: "text"
});

/*
send form data via ajax and return the data to callback function 
*/
function send_form( name , func )
{
    var url = $('#'+name).attr('action');
    
    var params = {};
    $.each( $('#'+name).serializeArray(), function(index,value) 
    {
        params[value.name] = value.value;
    });
    
    
    $.post( url , params , func );  
}

/*
send form data via ajax and show the return content to pop div 
*/

function send_form_pop( name )
{
    return send_form( name , function( data ){ show_pop_box( data ); } );
}

/*
send form data via ajax and show the return content in front of the form 
*/
function send_form_in( name )
{   
    return send_form( name , function( data ){ set_form_notice( name , data ) } );
}


function set_form_notice( name , data )
{
    data = '<span class="label label-important">' + data + '</span>';
    
    if( $('#form_'+name+'_notice').length != 0 )
    {
        $('#form_'+name+'_notice').html(data);
    }
    else
    {
        var odiv = $( "<div class='form_notice'></div>" );
        odiv.attr( 'id' , 'form_'+name+'_notice' );
        odiv.html(data);
        // $('#'+name).prepend( odiv );
        $('#'+name).after( odiv );
    } 
    
}


function show_pop_box( data , popid )
{
    if( popid == undefined ) popid = 'lp_pop_box'
    //console.log($('#' + popid) );
    if( $('#' + popid).length == 0 )
    {
        var did = $('<div><div id="' + 'lp_pop_container' + '"></div></div>');
        did.attr( 'id' , popid );
        did.css( 'display','none' );
        $('body').prepend(did);
    } 
    
    if( data != '' )
        $('#lp_pop_container').html(data);
    
    var left = ($(window).width() - $('#' + popid ).width())/2;
    
    $('#' + popid ).css('left',left);
    $('#' + popid ).css('display','block');
}

function hide_pop_box( popid )
{
    if( popid == undefined ) popid = 'lp_pop_box'
    $('#' + popid ).css('display','none');
}

function remember()
{
    $("input.remember").each( function()
    {
        // read cookie
        if( $.cookie( 'tt2-'+$(this).attr('name')) == 1)
        {
            $(this).attr('checked','true');
        }

        // save cookie
        

        $(this).unbind('click');
        $(this).bind('click',function(evt)
        {
            if( $(this).is(':checked') )
                $.cookie( 'tt2-'+$(this).attr('name') , 1  );
            else
                $.cookie( 'tt2-'+$(this).attr('name') , 0  );
        });

    });

}
/**
  
*/

// *-*-*-*-*-*-*-*-*-*-*-*-* for this app code end

function show_val(m,v) {
    if(v!=undefined && v!=''){
        return m+v;
    }
    return '';
}


function wait_ajax(op_key){
    if(ls_v(op_key)!='ok'){
    	$("#ajax_debug").append('#');
        setTimeout("wait_ajax('"+op_key+"')",100);
    }else{
        setTimeout('show_info()',100);
    }
}

var last_ajax_url=null;
var last_ajax_time=null;
var ajax_interval_time=9*1000;

// Dictionaries, used to populate select box or check for duplicate entries.
var ajax_op = /** @dict */ Object.create( null );
// if ( ! dict_list[ b ] ) dict_list[ b ] = 1; else ++dict_list[ b ];

function ajax_load(op_key,callBack){
	return ajaxApi(op_key,'',callBack);
}

function ajaxLoadDefaultCallBack(jsonObj){
    shdic.log.debug('in ajaxLoadDefaultCallBack()');
    var text = JSON.stringify(jsonObj);
    debug_log(text);
    
    var jd=jsonObj.data;
    var src = jd.msg;
    // alert(src);
    hotMsg(src);        
    // ClsWait();
};

function ajaxApi(op_key,data,callBack){
    
    var token = ls_v('token',0);
    var uid = ls_v('uid',0);
    if (token && uid && token.length>9){
        //base check
    }else{
    	// alert('登陆信息已经失效！');
    	autoClsMsg('登陆信息已经失效！#ajax_load ,'+token+','+uid);
    	ls_del('token');
	// appcan.window.close(1,500);
        return false;
    }

    appcan.locStorage.setVal(op_key,'wait');

    var api_root=get_server_root();
    var api = api_root+'/apps/survival_camp_v1/index.php?c=api';
    var pc_url = api + '&a='+op_key+'&token='+token+'&uid='+uid;

    //限制短时间内重复读取
    if(pc_url==last_ajax_url){        
        var now = new Date().getTime();
        var diffValue = now - last_ajax_time;
        if(diffValue<ajax_interval_time){
        	alert('刷新的太快了，休息几秒再试吧！');
			
			if(ajax_op[pc_url]){
        		var tt=ajax_op[pc_url];
        		if(callBack!=undefined){
					callBack(tt);
	        	}else{
	        		ajaxLoadDefaultCallBack(tt);
	        	}
	            ret = true;
	            appcan.locStorage.setVal(op_key,'ok');
	            $("#ajax_debug").append('');
        	}
			// ClsWait();
            return false;
        }
    }
    last_ajax_url=pc_url;
    last_ajax_time=now;

	if(data) pc_url = pc_url + data;

    var ret=false;

    AJAX.get(pc_url+'&seed='+Math.random(),function(res2){
        // alert(res2); 
        var tt=str2json(res2);
        if(tt && tt.err_code=='0'){
        	ajax_op[pc_url]=tt;
        	if(callBack!=undefined){
				callBack(tt);
        	}else{
        		ajaxLoadDefaultCallBack(tt);
        	}
            ret = true;
            appcan.locStorage.setVal(op_key,'ok');
            $("#ajax_debug").append('');
        }else{
        	alert('Error!!! '+res2);
        }
    },function(){
        alert('AJAX失败！请检查网络是否畅通！#'+op_key);  
    });
    //alert('func exit');
    ClsWait();
    return true;
}



var timeoutHandle=null;
function autoClsMsg(msg,t){
    // uexWindow.toast(1,5,msg,0);    
    if(!t){
    	t=1500;
    }else if(t<10){
  		t=t*1000;
    }
    $.Prompt(msg,t);
    if(timeoutHandle) clearTimeout(timeoutHandle);
    timeoutHandle=setTimeout('ClsWait()',t);
}


function hotMsg(src,t){
	$("#hot_msg").html(src);
	if(t){
		if(t<16) t=t*1000;
		setTimeout('resetHotMsg()',t);
	}else{
		setTimeout('resetHotMsg()',2000);	
	}	
}
function resetHotMsg(){
	$("#hot_msg").html('');
}

var isArray = function(obj) { 
	return Object.prototype.toString.call(obj) === '[object Array]'; 
}

function debug_log(text){
  try{
    var tt = ls_v('debug_mode');
    if(tt=='1'){
    	var tt=$("#div_debug");
    	if(tt.length>1) $("#div_debug").html(text).show();
    	var tt=$("#ajax_debug");
        if(tt.length>1) $("#ajax_debug").html(text).show();
    }else{
        $("#div_debug").hide();
        $("#ajax_debug").hide();
    }
  }catch(e){
  	console.log(text);
  };	
}

function makeTmpTable(jsonData,ud_desc,selector){
    var jd=jsonData;
    var src = '';
    var tr_att = ' height="50px"';
    src = '<table id="tmptable1" class="tmptable"><tbody>';
    src = src + '<tr'+tr_att+' class="head">';
    src = src + get_td_cell(' ','#' );
    var count=0;
    $.each(ud_desc,function(idx,item){ 
        src = src + get_td_cell(' ',item);
        count++;
    });
    src = src + '</tr>';
    if(selector){
        $(selector).html(src);    
    }    

    if(isArray(jd)){
        var i2=0;
        $.each(jd,function(idx,item){ 
            var tmp = item;
            i2 = i2+1;
            src = src + '<tr'+tr_att+' class="body">';
            src = src + get_td_cell('','#'+i2 );
            $.each(ud_desc,function(idx1,item1){ 
                var tt = getJsonAtt(tmp,idx1);
                src = src + get_td_cell(' ',tt);
            });
            src = src + '</tr>';
        });
    };
    
    if(selector){
        $(selector).html(src);    
    } 
    return src;
};

function get_td_cell(att,tit){
    if(!tit) tit='&nbsp;';
    return '<td'+att+'>'+tit+'</td>';
}

/******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ********/

function gid(id) {return typeof(id)=="string"?document.getElementById(id):id;}
 
function appendZero(n){return(("00"+ n).substr(("00"+ n).length-2));}//日期自动补零程序
 
//默认时间格式
function getJsDate(){
    var now = new Date();
    //year = now.getYear();
    var year = now.getFullYear();
    var month = now.getMonth();
    var mdate = now.getDate();
    var month = month +1;
    return year+"-"+appendZero(month)+"-"+appendZero(mdate);
}
 
function getJsTime(){
    var now = new Date();
    var h = now.getHours(), m = now.getMinutes(), s = now.getSeconds();
  return  appendZero(h) +":"+ appendZero(m) +":"+ appendZero(s);
}
 
function getFullTime(){
    return getJsDate()+' '+getJsTime();
}
function debug(log){
    var log=getFullTime()+' '+log
    console.log(log);
    $('#ajax_debug').append('<br/>'+log);
    return log;
}